package com.example.springboot_demo.exception;

import com.example.springboot_demo.utils.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.quartz.QuartzTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Component
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 参数校验不通过
     *
     * @param e BindException
     * @return AjaxResult
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handlerBindException(BindException e) {
        return AjaxResult.error(this.buildMsg(e.getBindingResult()));
    }

    /**
     * 参数校验不通过
     *
     * @param e MethodArgumentNotValidException
     * @return AjaxResult
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return AjaxResult.error(this.buildMsg(e.getBindingResult()));
    }

    /**
     * 参数校验不通过
     *
     * @param e ConstraintViolationException
     * @return AjaxResult
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public AjaxResult handlerConstraintViolationException(ConstraintViolationException e) {
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义异常
     *
     * @param e SpringBootDemoException
     * @return AjaxResult
     */
    @ExceptionHandler(SpringBootDemoException.class)
    public AjaxResult handlerSpringBootDemoException(SpringBootDemoException e) {
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 捕获顶级异常处理
    */
    @ExceptionHandler(Throwable.class)
    public AjaxResult handlerThrowable(Throwable e) {
        log.error("{}",e);
        return AjaxResult.error(e.getMessage());
    }



    /**
     * 构建参数错误提示信息
     *
     * @param bindingResult BindingResult
     * @return String
     */
    private String buildMsg(BindingResult bindingResult) {
        StringBuilder builder = new StringBuilder(32);
        for (FieldError error : bindingResult.getFieldErrors()) {
            builder.append(", [").append(error.getField()).append(":").append(error.getDefaultMessage()).append("]");
        }
        return builder.substring(2);
    }

}
